﻿// Decompiled with JetBrains decompiler
// Type: MCM.LightInject.LightInjectGenericServiceProvider
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using BUTR.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

#nullable enable
namespace MCM.LightInject
{
  internal class LightInjectGenericServiceProvider : IGenericServiceProvider, IDisposable
  {
    private static readonly LightInjectGenericServiceProvider.ReferenceEqualityComparer Comparer = new LightInjectGenericServiceProvider.ReferenceEqualityComparer();
    private static readonly ConcurrentDictionary<Type, object> OfTypeCache = new ConcurrentDictionary<Type, object>();
    private readonly IServiceContainer _serviceContainer;

    public LightInjectGenericServiceProvider(IServiceContainer serviceContainer)
    {
      this._serviceContainer = serviceContainer;
    }

    public IGenericServiceProviderScope CreateScope()
    {
      return (IGenericServiceProviderScope) new LightInjectGenericServiceProviderScope(this._serviceContainer.BeginScope());
    }

    public TService? GetService<TService>() where TService : class
    {
      TService instance = this._serviceContainer.GetInstance<TService>();
      Type type = typeof (TService);
      IEnumerable source;
      int num;
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>))
      {
        source = (object) instance as IEnumerable;
        num = source != null ? 1 : 0;
      }
      else
        num = 0;
      return num != 0 ? ((LightInjectGenericServiceProvider.OfTypeDelegate<TService>) LightInjectGenericServiceProvider.OfTypeCache.GetOrAdd(typeof (TService), (Func<Type, object>) (x => (object) typeof (Enumerable).GetMethod("OfType").MakeGenericMethod(x.GenericTypeArguments[0]).CreateDelegate(typeof (LightInjectGenericServiceProvider.OfTypeDelegate<TService>)))))(source.Cast<object>().Distinct<object>((IEqualityComparer<object>) LightInjectGenericServiceProvider.Comparer)) : instance;
    }

    public void Dispose() => this._serviceContainer.Dispose();

    private class ReferenceEqualityComparer : IEqualityComparer<object>
    {
      bool IEqualityComparer<object>.Equals(object x, object y) => x == y;

      int IEqualityComparer<object>.GetHashCode(object obj) => obj.GetHashCode();
    }

    private delegate TService OfTypeDelegate<TService>(IEnumerable<object> enumerable);
  }
}
